﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common;
using Microsoft.AspNetCore.Http;
using System.Net;
using Common.Helper;

namespace Quartz.Manage
{
    /// <summary>
    /// 登录验证拦截器
    /// </summary>
    public class GlobalAuthorizeAttribute : ActionFilterAttribute
    {
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string AdminUserName = ConfigHelper.Configuration["AdminUserName"];
            string AdminPwd = ConfigHelper.Configuration["AdminPwd"];
            if (AdminUserName.IsNullOrWhiteSpace())
            {
                AdminUserName = "admin";
            }
            if (AdminPwd.IsNullOrWhiteSpace())
            {
                AdminPwd = "123456";
            }
            var cookie = context.HttpContext.Request.Cookies["Quartz.Admin"];
            if (!cookie.IsNullOrWhiteSpace())
            {
                AdminModel admin = AESEncryptHelper.Decode(cookie).ToObject<AdminModel>();
                if (admin != null)
                {
                    if (admin.UserName == AdminUserName &&admin.Pwd== AdminPwd)
                    {
                        await base.OnActionExecutionAsync(context, next);
                        return;
                    }
                }
            }
            NoLogin(context);
            return;
        }

        private void NoLogin(ActionExecutingContext context)
        {
            if (context.HttpContext.Request.IsAjax())
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                context.HttpContext.Response.ContentType = "application/json;charset=UTF-8";
                context.HttpContext.Response.WriteAsync(new ApiResult
                {
                    Success = false,
                    Message = "未登录，请登录之后再试",
                    StatusCode = (int)ApiEnum.Unauthorized
                }.ToJson()).Wait();
            }
            else
            {
                context.Result = new RedirectResult("/home/login");
                return;
            }
        }
    }
}
